package com.lwl.Algorithmic_data_structure.class04归并;

import com.lwl.Utils.PrintUtil;

public class Code01MergeSort {

    public static void main(String[] args) {
        int[] arr = {2, 3, 1, 4, 5, 6, 7, 8, 9, 6, 3, 1, 5, 6, 3, 1};
        mergeSort(arr);
        PrintUtil.printArray(arr);
    }

    public static void mergeSort(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return;
        }
        process(arr, 0, arr.length - 1);
    }

    public static void process(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = left + ((right - left) >> 1);
        process(arr, left, mid);
        process(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }

    public static void merge(int[] arr, int left, int mid, int right) {
        // 辅助数组
        int helpArrayLen = right - left + 1;
        int[] help = new int[helpArrayLen];
        // 两个指针 左指针 <= mid,右指针 <= right
        int p1 = left;
        int p2 = mid + 1;
        // 填入当前辅助数组的指针
        int helpIndex = 0;
        while (p1 <= mid && p2 <= right) {
            help[helpIndex++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= mid) {
            help[helpIndex++] = arr[p1++];
        }
        while (p2 <= right) {
            help[helpIndex++] = arr[p2++];
        }
        for (int i = 0; i < helpArrayLen; i++) {
            arr[left + i] = help[i];
        }
    }

}
